<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        // 将空格替换成 %20
        // let str = "We are happy."
        // function solution(str) {
        //     let cstr = str
        //     let res = []
        //     for(let i=0; i<cstr.length; i++) {
        //         if (cstr.charCodeAt(i) === 32) {
        //             res.push('%20')
        //         } else {
        //             res.push(cstr[i])
        //         }
        //     }
        //     return res.join('')
        // }
        // const res = solution(str)
        // console.log(res)

        let str = "We are happy."
        function solution(str) {
            const arr = Array.from(str)
            let count = 0 
            for(let i=0; i<arr.length;i++) {
                if (arr[i] === ' ') {
                    count++
                }
            }
            console.log(count)
            let left = arr.length - 1
            let right = arr.length + count * 2 - 1
            while(left >= 0) {
                if (arr[left] === ' ') {
                    arr[right--] = '0'
                    arr[right--] = '2'
                    arr[right--] = '%'
                    left--
                } else {
                    arr[right--] = arr[left--]
                }
            }
            return arr.join('')
        }
        const res = solution(str)
        console.log(res)
    </script>
</body>
</html>